package com.sdx.demo.web;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.file.FileService;
import com.ibeetl.admin.core.util.DateUtil;
import com.ibeetl.admin.core.util.ValidateConfig;
import com.ibeetl.admin.core.web.AuthorizedBaesController;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.admin.core.web.JsonReturnCode;
import com.sdx.common.utils.FileUtils;
import com.sdx.common.utils.JacksonUtils;
import com.sdx.demo.entity.DemoBase;
import com.sdx.demo.service.DemoBaseService;
import com.sdx.demo.web.query.DemoBaseQuery;
import com.sdx.service.ConfigService;
import org.apache.commons.lang3.StringUtils;
import org.beetl.sql.core.engine.PageQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * 样例 接口
 */
@RequestMapping("/demo/demoBase")
@Controller
public class DemoBaseController extends AuthorizedBaesController{
	private static final Logger log = LoggerFactory.getLogger(DemoBaseController.class);
    private static final String MODEL = "/demo/demoBase";


    @Resource
	private DemoBaseService demoBaseService;
    
    @Resource
    FileService fileService;
    /* 页面 */

    @GetMapping("/index.do")
    @Function("demo.demoBase.query")
    @ResponseBody
    public ModelAndView index() {
	    System.out.println(ConfigService.fileUrl);
        ModelAndView view = new ModelAndView(MODEL+"/index.html") ;
        return view;
    }

    @GetMapping("/edit.do")
    @Function("demo.demoBase.edit")
    @ResponseBody
    public ModelAndView edit(Integer demoId) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        DemoBase demoBase = demoBaseService.queryById(demoId);
        view.addObject("demoBase", demoBase);
		try {
			view.addObject("demoBaseJson", JacksonUtils.toJsonString(demoBase,JacksonUtils.DF1));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
        return view;
    }

    @GetMapping("/add.do")
    @Function("demo.demoBase.add")
    @ResponseBody
    public ModelAndView add() {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        return view;
    }

    /* ajax json */

    @PostMapping("/list.json")
    @Function("demo.demoBase.query")
    @ResponseBody
    public JsonResult<PageQuery> list(DemoBaseQuery condtion)
    {
        PageQuery page = condtion.getPageQuery();
        demoBaseService.queryByCondition(page);
        return JsonResult.success(page);
    }

    private JsonResult save(boolean isNew,DemoBase demoBase,HttpServletRequest request
							,MultipartFile localFileFile
							,MultipartFile cloudFileFile
							,MultipartFile coverFile
	) {
    	JsonResult result = JsonResult.success();
		String dir = DateUtil.now("yyyyMMdd");
    	String subPath = "/images/cover/"+dir+"/";
		if (!FileUtils.isEmptyFile(localFileFile)) {
			try
			{
		        String localFileFileNamePair = FileUtils.upload(subPath,localFileFile);
		        String localFileStoreFile = localFileFileNamePair.split("::")[0];
		        localFileStoreFile = subPath+localFileStoreFile;
				demoBase.setLocalFile(localFileStoreFile);
			}catch(Exception e) {
				e.printStackTrace();
				result.setCode(JsonReturnCode.IO_ERROR.getCode());
				result.setMsg(e.getMessage());
			}
		}
		if (!FileUtils.isEmptyFile(cloudFileFile)) {
			try
			{
		        String cloudFileFileNamePair = FileUtils.upload(subPath,cloudFileFile);
		        String cloudFileStoreFile = cloudFileFileNamePair.split("::")[0];
		        cloudFileStoreFile = subPath+cloudFileStoreFile;
				demoBase.setCloudFile(cloudFileStoreFile);
			}catch(Exception e) {
				e.printStackTrace();
				result.setCode(JsonReturnCode.IO_ERROR.getCode());
				result.setMsg(e.getMessage());
			}
		}
		if (!FileUtils.isEmptyFile(coverFile)) {
			try
			{
		        String coverFileNamePair = FileUtils.upload(subPath,coverFile);
		        String coverStoreFile = coverFileNamePair.split("::")[0];
		        coverStoreFile = subPath+coverStoreFile;
				demoBase.setCover(coverStoreFile);
			}catch(Exception e) {
				e.printStackTrace();
				result.setCode(JsonReturnCode.IO_ERROR.getCode());
				result.setMsg(e.getMessage());
			}
		}
		CoreUser user = getLoginUser(request);

    	if (isNew) {
			demoBase.setCreatedBy(user.getId().intValue());
			demoBase.setCreatedName(user.getName());
			demoBase.setCreatedTime(new Date());
			demoBaseService.save(demoBase);
		} else {
			demoBase.setUpdatedBy(user.getId().intValue());
			demoBase.setUpdatedName(user.getName());
			demoBase.setUpdatedTime(new Date());
			demoBaseService.updateTemplate(demoBase);
		}
		return result;
	}
    @PostMapping("/add.json")
    @Function("demo.demoBase.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)DemoBase demoBase,HttpServletRequest request
							,@RequestParam("localFileFile") MultipartFile localFileFile
							,@RequestParam("cloudFileFile") MultipartFile cloudFileFile
							,@RequestParam("coverFile") MultipartFile coverFile
		)
    {

        return save(true,demoBase,request
					,localFileFile
					,cloudFileFile
					,coverFile
		);
    }

    @PostMapping("/update.json")
    @Function("demo.demoBase.edit")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  DemoBase demoBase,HttpServletRequest request
							,@RequestParam("localFileFile") MultipartFile localFileFile
							,@RequestParam("cloudFileFile") MultipartFile cloudFileFile
							,@RequestParam("coverFile") MultipartFile coverFile
		) {
		return save(false,demoBase,request
		,localFileFile
		,cloudFileFile
		,coverFile
		);
    }


   
    @GetMapping("/view.json")
    @Function("demo.demoBase.query")
    @ResponseBody
    public JsonResult<DemoBase>queryInfo(Integer demoId) {
        DemoBase demoBase = demoBaseService.queryById( demoId);
        return  JsonResult.success(demoBase);
    }

    @PostMapping("/delete.json")
    @Function("demo.demoBase..del")
    @ResponseBody
    public JsonResult delete(String ids) {
        if (ids.endsWith(",")) {
            ids = StringUtils.substringBeforeLast(ids, ",");
        }
        //List<Long> idList = ConvertUtil.str2longs(ids);
		List<String> idList = new ArrayList<String>();
		Collections.addAll(idList,ids.split(","));
        demoBaseService.batchDelDemoBase(idList);
        return JsonResult.success();
    }
    

}
